/*
  (C) 2007 - Boston University
  Contact: Michael Ocean 

  This work is a part of the larger snBench project.  Information
  can be found at: http://csr.bu.edu/snbench 

  This program is free software; you can redistribute it and/or
  modify it under the terms of Version 2 of the GNU General Public 
  License.
  
  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  General Public License for more details.
  
  You should have received a copy of the GNU Library General Public
  License along with this library; if not, write to the Free
  Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package stepide;

import org.jgraph.JGraph;
import java.awt.Dimension;
import java.awt.print.PageFormat;
import javax.swing.RepaintManager;
import java.awt.Graphics;
import java.awt.print.Printable;
import javax.swing.JComponent;

/**
	Overview: This class is required by JGraph in order to support printing of the graph.  The
	code was selected from the JGraph user manual.
*/
public class PrintableStepGraph extends JComponent implements Printable {
	private static final long serialVersionUID = 20070428;
	private JGraph _graph = null;

	public PrintableStepGraph(JGraph graph) {
		_graph = graph;
	}

	/**
		Prints the JGraph. This method is not called directly by any user code and is instead called by JGraph internally.
	*/
	public int print(Graphics g, PageFormat printFormat, int page) {
		int pageScale = 1;

		Dimension pSize = _graph.getPreferredSize();
		int w = (int) (printFormat.getWidth() * pageScale);
		int h = (int) (printFormat.getHeight() * pageScale);
		int cols = (int) Math.max(Math.ceil((double) (pSize.width - 5) / (double) w), 1);
		int rows = (int) Math.max(Math.ceil((double) (pSize.height - 5) / (double) h), 1);
		if (page < cols * rows) {
			// Configures graph for printing
			RepaintManager currentManager = RepaintManager.currentManager(this);
			currentManager.setDoubleBufferingEnabled(false);
			double oldScale = _graph.getScale();
			_graph.setScale(1 / pageScale);
			int dx = (int) ((page % cols) * printFormat.getWidth());
			int dy = (int) ((page % rows) * printFormat.getHeight());
			g.translate(-dx, -dy);
			g.setClip(dx, dy, (int) (dx + printFormat.getWidth()), (int) (dy + printFormat.getHeight()));

			_graph.paint(g);

			// Restores graph
			g.translate(dx, dy);
			_graph.setScale(oldScale);
			currentManager.setDoubleBufferingEnabled(true);
			return PAGE_EXISTS;
		}
		else {
			return NO_SUCH_PAGE;
		}
	}

}